package cn.my.learning.web;

import cn.my.learning.domain.NoteImage;
import cn.my.learning.domain.User;
import cn.my.learning.repository.ImageRepository;
import cn.my.learning.util.FileUtil;
import cn.my.learning.util.IsLoginUtil;
import cn.my.learning.util.UuidUtil;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Leo on 2017/3/22.
 * 文件图片管理类
 */

@RestController
public class FileController {

    @Autowired
    private ImageRepository imageRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    //logger类
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    //根目录
    private static final String ROOT = "static/image/uploadImage";

    //初始化头像上传路径(本地)
    @Value("${user.head-faviconImg.path}")
    private String localUploadPath;

    //初始化头像上传路径（项目）
    @Value("${user.head-faviconImg.projectPath}")
    private String projectUploadPath;

    //实例化资源加载器
    private final ResourceLoader resourceLoader;

    @Autowired
    public FileController(ResourceLoader resourceLoader, MongoTemplate mongoTemplate) {
        this.resourceLoader = resourceLoader;
        this.mongoTemplate = mongoTemplate;
    }

    @ApiOperation(value = "EditorMD的图片上传", httpMethod = "POST", notes = "EditorMD的图片上传")
    @ResponseBody
    @PostMapping(value = "/image")
    public void imgUploder(HttpServletRequest httpServletRequest, HttpServletResponse response, @RequestParam(value = "editormd-image-file") MultipartFile attach) throws IOException, IllegalStateException{

        //获取用户名并初始化userFolderName
        IsLoginUtil isLoginUtil = new IsLoginUtil();
        String userFolderName = isLoginUtil.IsLogin(httpServletRequest);

        //获取File对象(默认用户路径下)
        File userFolderPath = new File(ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/image/uploadImage/" + userFolderName);

        //获取文件名
        String fullfileName = attach.getOriginalFilename();
        logger.info("上传的文件名为：" + fullfileName);

        // 获取文件的后缀名
        String suffixName = fullfileName.substring(fullfileName.lastIndexOf("."));
        logger.info("上传的后缀名为：" + suffixName);


        //文件上传后的路径
        try {
            if (!userFolderPath.exists()) {
                logger.info("目录不存在");
                userFolderPath.mkdirs();
            }
        } catch (Exception e){
            e.printStackTrace();
        }

        String newName = UuidUtil.get32UUID();
        File destination = new File(userFolderPath + "/" + newName + suffixName);
        logger.info(destination.toString());

        //上传到服务器本地
        attach.transferTo(destination);

        //返回给前台的json验证以及图片的地址
        response.getWriter().write( "{\"success\": 1, \"message\":\"Success\",\"url\":\"/image/uploadImage/" + userFolderName + "/" + newName + suffixName + "\"}" );

        //获取当前时间，并格式化
        String uploadTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        //实例化参数
        NoteImage image = new NoteImage();

        image.setPubName(userFolderName);
        image.setUploadImgName(fullfileName);
        image.setUploadImgType(suffixName);
        image.setUploadImgUUID(newName);
        image.setUploadImgAbsolutePath(destination.toString());
        image.setUploadTime(uploadTime);
        image.setUse(Boolean.FALSE);

        //插入到数据库中
        imageRepository.save(image);

    }

    @ApiOperation(value = "图片GET", httpMethod = "GET", notes = "图片GET")
    @GetMapping(value = "/image/../{filename:.+}")
    @ResponseBody
    public ResponseEntity<?> getFile(@PathVariable String filename) {
        logger.info(filename);
        try {
            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(ROOT, filename).toString()));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    @ApiOperation(value = "头像上传", httpMethod = "POST", notes = "头像上传")
    @PostMapping(value = "/head_favicon")
    @ResponseBody
    public boolean faviconImg(HttpServletRequest httpServletRequest, @RequestParam(value = "file") MultipartFile multipartFile) throws IOException{

        //获取用户名
        String account = new IsLoginUtil().IsLogin(httpServletRequest);

        //项目文件名
        String destination = localUploadPath + account + "\\";

        // 获取文件的后缀名
        String suffixName = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));

        //文件上传后的路径
        try {
            //删除默认头像
            boolean IsDeleteDefaultImg = new File(destination + "userInfo.png").delete();

            //删除成功后，将新头像传到用户文件夹下并更新头像
            if (IsDeleteDefaultImg){
                //头像双备份，服务器一份target一份
                String headImgAbsolutePath =  destination + "userInfo" + suffixName;

                //上传到项目
                multipartFile.transferTo(new File(headImgAbsolutePath));

                //头像格式转换
                new FileUtil().Conversion(suffixName.replace(".",""), destination + "userInfo");

                //上传到服务器缓存
                /*
                 * 第一参数为from路径，第二个参数为to路径
                 */
                new FileUtil().copyFile(localUploadPath + account + "\\" + "userInfo.png",
                                        projectUploadPath + account);

                //MongoDB更新语句
                mongoTemplate.upsert(new Query(Criteria.where("account").is(account)),new Update().set("headImg", "image\\userImage\\" + account + "\\" + "userInfo.png"), User.class);

                return true;
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
}
